//
//  TSZUserAcountModel.swift
//  微博天下

import UIKit

class TSZUserAcountModel: NSObject , NSCoding {
    
    //用户是否登录
    class var userLogin: Bool {
        return sharedUserAccount() != nil
    }
    
    //用于存储根据授权码返回来的一个字典中的值  Optional(["access_token": 2.00fIMOPGj8luwCf208762f4b08mpEy, "remind_in": 157679999, "uid": 5721825289, "expires_in": 157679999])
    
    //访问令牌
    var access_token:String?
    //remind_in expires_in都是access_token的周期方法，但是remind_in 要被废弃  了
    //NSNumber 类型的
    var expires_in: NSTimeInterval = 0
        {
        didSet{
    //初始化过期时间
    expiresDate = NSDate(timeIntervalSinceNow: expires_in)
                    }
    }
    //uid 用户唯一标识符
    var uid: String?
    //用户微博的名称
    var name: String?
    //用户头像的地址
    var avatar_large: String?
    
    //过期时间，因为我们的授权是有限制的
    var expiresDate:NSDate?
    
    //WARK - 进行字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        
        //字典转模型
        setValuesForKeysWithDictionary(dict)
        //初始化过期时间
//        expiresDate = NSDate(timeIntervalSinceNow: expires_in)

         // 设置全局的用户信息
        TSZUserAcountModel.userAccount = self
    }
    //需要实现下列这个运行时方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //需要打印出来的话要自己重新定义despration方法
    override var description: String{
        let properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    //加载用户信息 ，异步获取用户的附加信息，保存用户信息
    func loadUserInfo(finished: (error: NSError?) ->()){
        TSZNetWorkTools.sharedNetWorkTools.loadUserInfo(uid!) { (result, error) -> () in
            //有错误就提
            if let dict = result {
                //设置用户信息
                self.name = dict["name"]as? String
                self.avatar_large = dict["avatar_large"] as? String
                //保存信息
                self.saveAccount()
            }
            
            //完成回调
            finished(error: error)
            
        }
    }
    //MARK保存到document中
    //1、获取沙盒路径
    private static let docuPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/accountInfo.plist")
    
    //归档 ,保存账户信息，类方法
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: TSZUserAcountModel.docuPath)
    }
    
    //设置一个全局的账户
    private static var userAccount:TSZUserAcountModel?
    //判断用户属性
    class func sharedUserAccount() ->TSZUserAcountModel?{
        if userAccount == nil{
            //解档
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(docuPath) as? TSZUserAcountModel
        }
        
        //如果时间过期就把帐号设为nil
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{ //升序 就是  已过期
            userAccount = nil
        }
        return userAccount
    }
    
    
//    //加载账户信息
//     func loadAccount() ->TSZUserAcountModel?{
//        return (NSKeyedUnarchiver.unarchiveObjectWithFile(TSZUserAcountModel.docuPath) as? TSZUserAcountModel)
//    }
    
    //把我们从授权服务器返回的数据字典转为模型保存起来 ，使用归档 
    func encodeWithCoder(enCoder: NSCoder) {
       enCoder.encodeObject(access_token, forKey: "access_token")
       enCoder.encodeDouble(expires_in, forKey: "expires_in")
       enCoder.encodeObject(uid, forKey: "uid")
        enCoder.encodeObject(expiresDate, forKey: "expiresDate")
        enCoder.encodeObject(name, forKey: "name")
        enCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder deCode: NSCoder) {
        access_token = deCode.decodeObjectForKey("access_token") as? String
        expires_in = deCode.decodeDoubleForKey("expires_in")
        
        uid = deCode.decodeObjectForKey("uid") as? String
        expiresDate = deCode.decodeObjectForKey("expiresDate")as? NSDate
        name = deCode.decodeObjectForKey("name") as? String
        avatar_large = deCode.decodeObjectForKey("avatar_large") as? String
    }
}
